package biz

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"
)

type Node struct {
	Name       string `json:"name"`
	Address    string `json:"address"`
	SessionNum int64  `json:"sessionNum"`
}

type EtcdPoint struct {
	Endpoints []string `json:"endpoints"`
}

type ClusterInfo struct {
	Nodes []Node    `json:"nodes"`
	Etcd  EtcdPoint `json:"etcd"`
	Cid   string    `json:"cid"`
}

type SessionNumRsp struct {
	Result int64 `json:"result"`
}

func GetClusterInfo(cid string) (*ClusterInfo) {
	var ip string
	if "Hangzhou" == cid {
		ip = "10.18.0.57"
	} else if "Frankfurt" == cid {
		ip = "172.18.2.138"
	} else {
		log.Println("集群Id不正确!", cid)
		return nil
	}
	client := &http.Client{Timeout: 5 * time.Second}
	req, _ := http.NewRequest("GET", "http://"+ip+":9103/api/v1/cluster/info", nil)
	req.Header.Add("content-type", "application/json");
	resp, err := client.Do(req)
	if err != nil {
		log.Println(err)
		return nil
	}
	defer resp.Body.Close()

	info := &ClusterInfo{}
	result, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(result, info)
	length := len(info.Nodes)
	Ndes := make([]Node, length)
	for i := 0; i < length; i++ {
		node := info.Nodes[i]
		node.SessionNum = GetNodeSessionNum(node.Address)
		Ndes[i] = node
	}
	info.Nodes = Ndes
	info.Cid = cid
	return info
}

func GetNodeSessionNum(adrr string) int64 {
	split := strings.Split(adrr, ":")
	ip := split[0]
	client := &http.Client{Timeout: 5 * time.Second}
	req, _ := http.NewRequest("GET", "http://"+ip+":9103/api/v1/session/nums", nil)
	req.Header.Add("content-type", "application/json");
	resp, err := client.Do(req)
	if err != nil {
		log.Println(err)
		return 0
	}
	defer resp.Body.Close()

	numRsp := &SessionNumRsp{}
	result, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(result, numRsp)
	return numRsp.Result
}
